package com.fly.hbn.dao.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fly.hbn.dao.CustomerDao;
import com.fly.hbn.model.Customer;

@Repository
public class CustomerDaoImpl implements CustomerDao
{
    @Autowired
    private SessionFactory sessionFactory;
    
    public void setSessionFactory(SessionFactory sf)
    {
        this.sessionFactory = sf;
    }
    
    @Override
    public List<Customer> getAllCustomers()
    {
        Session session = sessionFactory.getCurrentSession();
        return session.createQuery("from Customer Order by id desc").list();
    }
    
    @Override
    public Customer getCustomer(int id)
    {
        Session session = sessionFactory.getCurrentSession();
        Customer customer = session.get(Customer.class, id);
        return customer;
    }
    
    @Override
    public Customer addCustomer(Customer customer)
    {
        Session session = sessionFactory.getCurrentSession();
        session.save(customer);
        return customer;
    }
    
    @Override
    public void updateCustomer(Customer customer)
    {
        Session session = sessionFactory.getCurrentSession();
        Hibernate.initialize(customer);
        session.update(customer);
    }
    
    @Override
    public void deleteCustomer(int id)
    {
        Session session = sessionFactory.getCurrentSession();
        Customer p = session.get(Customer.class, id);
        if (null != p)
        {
            session.delete(p);
        }
    }
}
